
import TokenCache from '@/utils/cache/TokenCache'

export function download (url, name = '') {
  // this.$http.get(url)
  // An highlighted block
  function createObjectURL (object) {
    return (window.URL) ? window.URL.createObjectURL(object) : window.webkitURL.createObjectURL(object)
  }

  const xhr = new XMLHttpRequest()
  const formData = new FormData()
  xhr.open('get', url) // url填写后台的接口地址，如果是post，在formData append参数（参考原文地址）
  xhr.setRequestHeader('Authorization', 'Bearer ' + TokenCache.getToken())
  xhr.responseType = 'blob'
  xhr.onload = function (e) {
    if (this.status === 200) {
      const blob = this.response
      const filename = name // 这里的名字，可以按后端给的接口固定表单设置一下名字，如（费用单.xlsx,合同.doc等等）
      if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, filename)
      } else {
        const a = document.createElement('a')
        const url = createObjectURL(blob)
        a.href = url
        a.download = filename
        document.body.appendChild(a)
        a.click()
        window.URL.revokeObjectURL(url)
      }
    }
  }
  xhr.send(formData)
}
